import pdfMake from 'pdfmake/build/pdfmake';
import htmlToPdfmake from 'html-to-pdfmake';
import font from 'pdfmake/build/vfs_fonts'
import {uploadFile} from "@/api";

//引入中文字体，避免转换的PDF中文乱码
//打包教程：https://www.cnblogs.com/xiangsj/p/18158319
pdfMake.fonts = {
  YaHei: {
    normal: 'Microsoft-YaHei.ttf',
    bold: 'Microsoft-YaHei.ttf',
    italics: 'Microsoft-YaHei.ttf',
    bolditalics: 'Microsoft-YaHei.ttf',
  }
};

pdfMake.vfs = font.pdfMake.vfs

export async function htmlMakePdf(html) {
  const dd = {
    content: htmlToPdfmake(html),
    defaultStyle: {
      font: 'YaHei'
    },
  };
  const pdf = pdfMake.createPdf(dd);
  // 下载到本地
  // pdf.download()
  let time = Date.parse(new Date())
  return new Promise((resolve, reject) => {
    pdf.getBlob(async (blob) => {
      let formData = new FormData();
      formData.append('file', blob, `file-${time}.pdf`);
      let response = await uploadFile(formData)
      if (response.code === 200) {
        resolve(response.data)
      }
    });
  })
}
